package com.d3works.apps.account.web;

import com.d3works.apps.account.service.YearControlService;
import com.d3works.apps.account.service.YearServiceAccountImpl;
import com.d3works.apps.base.db.Year;
import com.d3works.apps.base.db.repo.YearRepository;
import com.d3works.exception.ResponseMessageType;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;

@Singleton
public class YearController {

  public void close(ActionRequest request, ActionResponse response) {
    Year year = request.getContext().asType(Year.class);

    try {
      Beans.get(YearServiceAccountImpl.class).closeYearProcess(year);
      response.setReload(true);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void adjust(ActionRequest request, ActionResponse response) {
    Year year = request.getContext().asType(Year.class);

    try {
      Beans.get(YearServiceAccountImpl.class).adjust(year);
      response.setReload(true);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void controlDates(ActionRequest request, ActionResponse response) {
    try {
      Beans.get(YearControlService.class).controlDates(request.getContext().asType(Year.class));
    } catch (Exception e) {
      TraceBackService.trace(response, e, ResponseMessageType.ERROR);
    }
  }

  public void setReadOnly(ActionRequest request, ActionResponse response) {
    try {
      Year year =
          Beans.get(YearRepository.class).find(request.getContext().asType(Year.class).getId());
      if (year != null) {
        Boolean isInMove = Beans.get(YearControlService.class).isLinkedToMove(year);
        response.setAttr("fromDate", "readonly", isInMove);
        response.setAttr("toDate", "readonly", isInMove);
      }

    } catch (Exception e) {
      TraceBackService.trace(response, e, ResponseMessageType.ERROR);
    }
  }
}
